package com.chmingx.admin.controller;

import com.chmingx.admin.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class IndexController {
    // 登录页
    @GetMapping(value = {"/", "/login"})
    public String loginPage() {
        return "login";
    }

    // 处理登录请求
    @PostMapping("/login")
    public String login(User user, HttpSession session, Model model) {
        if (!user.getUserName().isEmpty() && "123456".equals(user.getPassword())) {
            session.setAttribute("loginUser", user);
            // return "index"; // 这种写法会造成刷新页面时重复提交请求, 改进：使用重定向
            return "redirect:index.html"; // 登录成功后重定向到index.html
        } else {
            model.addAttribute("msg", "账号或密码错误");
            return "login";
        }
    }

    // 去index.html
    @GetMapping("/index.html")
    public String mainPage(HttpSession session, Model model) {
        Object user = session.getAttribute("loginUser");
        if (user != null) {
            return "index";
        } else {
            model.addAttribute("msg", "请登录");
            return "login";
        }

    }
}
